package cn.lisens.listener;

import java.util.concurrent.atomic.AtomicLong;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class CustomServletRequestListener implements ServletRequestListener {

	private static final Logger logger = LoggerFactory.getLogger(CustomServletRequestListener.class);
    private final AtomicLong requestCount = new AtomicLong(0);

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        long count = requestCount.incrementAndGet();
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        
        // 将请求开始时间存入属性
        request.setAttribute("startTime", System.currentTimeMillis());
        
        if (logger.isDebugEnabled()) {
        	logger.debug("请求开始: {} {}, 总请求数: {}", 
        			request.getMethod(), request.getRequestURI(), count);
        }
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        Long startTime = (Long) request.getAttribute("startTime");
        
        if (startTime != null) {
            long duration = System.currentTimeMillis() - startTime;
            logger.info("请求完成: {} {}, 耗时: {}ms", 
                       request.getMethod(), request.getRequestURI(), duration);
            
            // 记录慢请求
            if (duration > 1000) {
                logger.warn("慢请求警告: {} {} 耗时 {}ms", 
                           request.getMethod(), request.getRequestURI(), duration);
            }
        }
    }
    
    public long getTotalRequestCount() {
        return requestCount.get();
    }
}
